package com.security.brows.room

import android.content.Context
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.hub.videobrowsdownload.BrowsApplication
import kotlinx.coroutines.flow.Flow

@Database(
    entities = [BrowsVideoDownloadBean::class, BrowsWebHistoryBean::class, BrowsWebFavoriteBean::class],
    version = 2,
    exportSchema = false,

)
abstract class BrowsRoomDatabase : RoomDatabase() {
    abstract fun dao(): BrowsVideoDao
}

@Dao
interface BrowsVideoDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(bean: BrowsVideoDownloadBean)
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(bean: BrowsWebHistoryBean)
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(bean: BrowsWebFavoriteBean)

    @Query("select * from web_favorite where url=:url")
    fun getFavoriteByUrl(url:String):BrowsWebFavoriteBean?
    @Query("select * from web_history where time=:time")
    fun getWebHistory(time:Long):BrowsWebHistoryBean?
    @Query("select * from web_history order by time desc")
    fun getWebHistoryFlow(): Flow<List<BrowsWebHistoryBean>>
    @Query("select * from web_favorite order by time desc")
    fun getWebFavoriteFlow(): Flow<List<BrowsWebFavoriteBean>>
    @Delete
    fun deleteWebHistory(list: List<BrowsWebHistoryBean>)
    @Delete
    fun deleteWebFavorite(bean:BrowsWebFavoriteBean)
    @Delete
    fun deleteWebHistory(bean:BrowsWebHistoryBean)

    @Query("delete  from download_file where id=:id")
    fun deleteById(id: Long)

    @Query("select * from download_file where downloadState=4 order by downloadSuccessTime desc")
    fun getDownloadedVideoFlow(): Flow<List<BrowsVideoDownloadBean>>

    @Query("select * from download_file where downloadState!=4 order by id desc")
    fun getDownloadingVideoFlow(): Flow<List<BrowsVideoDownloadBean>>

    @Query("select * from download_file where downloadState!=4 order by id desc")
    fun getDownloadingVideo(): List<BrowsVideoDownloadBean>

    @Query("select * from download_file where downloadState=4 and url=:url")
    fun getDownloadedVideoByUrl(url:String): BrowsVideoDownloadBean?
}

object BrowsRoomHelper {
    private var appDatabase: BrowsRoomDatabase? = null

    // 获取UserDao对象
    private var dao: BrowsVideoDao? = null

    fun getDao(context: Context = BrowsApplication.context): BrowsVideoDao {
        if (dao != null) {
            return dao!!
        }
        appDatabase =
            Room.databaseBuilder(
                context.applicationContext,
                BrowsRoomDatabase::class.java,
                "brows_video_download_db"
            )
                .allowMainThreadQueries()
                .addMigrations(MIGRATION_1_2)
                .build()
        dao = appDatabase!!.dao()
        return dao!!
    }

    private val MIGRATION_1_2: Migration = object : Migration(1, 2) {
        override fun migrate(db: SupportSQLiteDatabase) {
            db.execSQL("CREATE TABLE IF NOT EXISTS `web_history` (`time` INTEGER NOT NULL, `url` TEXT, `icon` TEXT, `title` TEXT, `icon_url` TEXT, PRIMARY KEY(`time`))")

            db.execSQL("CREATE TABLE IF NOT EXISTS `web_favorite` (`url` TEXT NOT NULL, `time` INTEGER NOT NULL,  `icon` TEXT, `title` TEXT, `icon_url` TEXT, PRIMARY KEY(`url`))")
        }
    }

}